import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
declare var BMap: any;
declare var BMapLib: any;
declare var toMapPointArr: any;
declare var BMAP_ANCHOR_BOTTOM_RIGHT:any;
@Component({
	selector: 'sa-history-query',
	templateUrl: './history-query.component.html',
})
export class HistoryQueryComponent implements OnInit {

	constructor(private jsonApiService: JsonApiService, private router: Router) {};
	deviceId: string = '';
	carNumber: string = '';
	spaceTime: number = 120;
	startTime: string = '';
	endTime: string = '';
	carlistArr = []; //所有车辆的数据
	markerClustererObj: any; //聚合能marker对象
	myMap: any; //地图对象
	mapSize: number = 10;
	//	表格部分参数
	isTable: boolean = false; //是否展开表格
	tableData = []; //table数据
	resultTableData: any = [];
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword	
	isDisable: boolean = false;
	isExpor: boolean = false; //是否显示下载数据
	exportUrl: string = '#';
	isload: boolean = false;
	btnData = []; //按钮权限集合
	downloadADValue: boolean = false;
	treeStatus: string = '收起'; //树形图展开或者收起状态
	btnDownTime: number = 0; //截留btn点击展开频率
	baiduInfoBox;

	carTreeData = []; //车辆树形图数据
	notOnlineCar = false;
	//初始化树形图数据
	findCarCount = 0; //车辆树搜出的总数
	findCarIndex = 0; //车辆树当前定位
	findString = ''; //搜索提示
	
	
	//接收子组件选中的车辆数据
	getCartreeMess(carMess){
		this.slectedCarEvent(carMess);
	}
	//选中一辆车事件
	slectedCarEvent(param) {
		this.deviceId = param.deviceId;
		this.carNumber = param.carNumber;
		this.findCar(this.deviceId);
		this.isTable = false;
	}
	//通过车辆的deviceId找到对应车辆并开启信息框
	findCar(deviceId) {
		let data = this.carlistArr;
		let len = data.length;
		for(let i = 0; i < len; i++) {
			let id = data[i].deviceId;
			if(id == deviceId) {
				this.openTextInfo(data[i]);
			}
		}
	}
	//初始化加载所有车辆,地图打点定位数据
	initAllCar() {
		this.jsonApiService.http("gps/getcarGpsInfoList.html", null).subscribe(result => {
			this.carlistArr = toMapPointArr(result);
			this.MarkerClusterer();
		})
	}
	//生成聚能合marker
	MarkerClusterer() {
		let markers = [];//marker点集合
		for(let i = 0; i < this.carlistArr.length; i++) {
			let obj = this.carlistArr[i];
			if(obj.lng && obj.lat) {
				let marker = new BMap.Marker(new BMap.Point(obj.lng, obj.lat), {
					icon: new BMap.Icon("assets/img/trackImage/car01.png", new BMap.Size(25, 25))
				}); // 创建标注
				let that = this;
				marker.addEventListener("click", function(e) {
					that.openTextInfo(obj);
				})
				markers.push(marker)
			}
		}
		this.markerClustererObj = new BMapLib.MarkerClusterer(this.myMap, {
			markers: markers
		});
	}
	//通过数据生成信息框
	openTextInfo(infoData) {
		var that = this;
		if(baiduInfoBox) {
			baiduInfoBox.close();
		}
		let reqUrl = config.BaseURL + 'realtime/getRealTimeData.html';
		let reqdata = {
			deviceId: infoData.deviceId
		};
		let weightUnit = ' 吨',
			deviceInfoData:any;
		$.ajax({
			type: "POST",
			data: reqdata,
			url: reqUrl,
			dataType: "json",
			async: false,
			xhrFields: {
				withCredentials: true
			},
			success: function(result) {
				if(result.data){
					let data = result.data;
					for(let item in data){
						data[item] = data[item]||'--';
					}
					deviceInfoData = data;
				}
				deviceInfoData.unit == '2' ? weightUnit = ' kg' : weightUnit = ' 吨';
			}         
		});
		deviceInfoData.uploadDate=deviceInfoData.uploadDate?deviceInfoData.uploadDate:deviceInfoData.gpsUploadDate;
		
		let params = 'deviceId=' + deviceInfoData.deviceId;
		this.jsonApiService.http("realtime/getRealTimeDataForBase.html", params).subscribe(resDate => {
			if(resDate.data.unit == '2') {
				weightUnit = ' kg';
			}
			if(resDate.data.unit == '1'){
				weightUnit = ' 吨';
			}
		});
		
		//警报类型切换，1，是司机断电		2，设备关机	其余返回空
		let alarmType = '';
		if(deviceInfoData.alarmType == '1'){
			alarmType = '断电警报';
		}
		if(deviceInfoData.alarmType == '2'){
			alarmType = '离线警报';
		}
		else{
			alarmType = '--';
		}
		// 在线离线判断
		let lineState = '';
		if(deviceInfoData.runStatus=='0'){
			lineState = '<span style="color:#333333;position:absolute;right:50px;background-color:#ffffff;height:34px;">[离线]</span>';
		}else{
			lineState = '<span style="color:#2bb56b;position:absolute;right:50px;background-color:#ffffff;height:34px;">[在线]</span>';
		}
		common.pointGetAdress(infoData).then(function(address) {
//			var html = '<div class="infoBox">' +
//				'<a></a>' +
//				'<div class="content">' +
//				'<ul>' +
//				'<li><span class="leftSpan">定位技术：</span><span class="rightSpan"> 北斗+GPS </span></li>' +
//				'<li><span class="leftSpan">公司名称：</span><span class="rightSpan"> ' + deviceInfoData.companyName + '</span></li>' +
//				'<li><span class="leftSpan">当前重量：</span><span class="rightSpan"> ' + common.twoDecimal(deviceInfoData.weight) + weightUnit + '</span></li>' +
//				'<li><span class="leftSpan">当前速度：</span><span class="rightSpan"> ' + deviceInfoData.speed + ' km/h</span></li>' +
//				'<li><span class="leftSpan">经纬度值：</span><span class="rightSpan"> ' + infoData.x + ',' + infoData.y + '</span></li>' +
//				'<li><span class="leftSpan">更新时间：</span><span class="rightSpan"> ' + deviceInfoData.uploadDate + '</span></li>' +
//				'<li><span class="leftSpan">当前位置：</span><span class="rightSpan"> ' + address + '</span></li>' +
//				'</ul>' +
//				'</div>' +
//				'</div>';
			var html = 
				'<div class=" BMap-info">' +
					'<p class="title"><img class="position-img" src="assets/img/bmap/position.png" />' + address + ' [北斗+GPS]</span>'+ lineState +
					'<div class="content">' +
						'<div class="contentText">' +
							'<ul class="row">' +
								'<li class="col-sm-4 module no-padding"><span class="li-lable">车牌号码</span><span class="li-value">'+deviceInfoData.carNumber+'['+deviceInfoData.deviceId+']</span></li>'+
								'<li class="col-sm-4 module no-padding"><span class="li-lable">公司名称</span><span class="li-value" style="white-space: nowrap;text-overflow: ellipsis;overflow: hidden;" title='+deviceInfoData.companyName+'>'+deviceInfoData.companyName+'</span></li>'+
								'<li class="col-sm-4 module no-padding"><span class="li-lable">定位时间</span><span class="li-value">'+deviceInfoData.carUploadDate+'</span></li>'+
								'<li class="col-sm-4 module no-padding"><span class="li-lable">当前重量</span><span class="li-value">'+common.twoDecimal(deviceInfoData.weight) + weightUnit+'</span></li>'+
								'<li class="col-sm-4 module no-padding"><span class="li-lable">报警类型</span><span class="li-value">'+alarmType+'</span></li>'+
								'<li class="col-sm-4 module no-padding"><span class="li-lable">报警时间</span><span class="li-value">'+deviceInfoData.alarmTime+'</span></li>'+
								'<li class="col-sm-4 module no-padding"><span class="li-lable">当前车速[km/h]</span><span class="li-value">'+deviceInfoData.speed+'</span></li>'+
								'<li class="col-sm-4 module no-padding"><span class="li-lable">电压[v]</span><span class="li-value">'+deviceInfoData.voltage+'</span></li>'+
								'<li class="col-sm-4 module no-padding"><span class="li-lable">电压采集时间</span><span class="li-value">'+deviceInfoData.voltageTime+'</span></li>'+
							'</ul>'+
						'</div>'+
					'</div>' +
				'</div>';
			var opts = {
				width: 508, // 信息窗口宽度
//				title: deviceInfoData.carNumber + " [ ID " + deviceInfoData.deviceId + "]", // 信息窗口标题	 
			}
			var infoWindow = new BMap.InfoWindow(html, opts); // 创建信息窗口对象 
			var point = new BMap.Point(infoData.lng, infoData.lat);
			that.myMap.openInfoWindow(infoWindow, point); //开启信息窗口
			setTimeout(function() {
				if($('.pointer').length < 1) {
					$('.BMap_bottom').append('<div class="pointer"></div>');
				}
			}, 50);
		})
	}
	
	table_search() {
		this.curPage = 1;
		this.load();
	}
	//表格部分  初始化加载list数据
	load() {
		if(this.isload) {
			this.jsonApiService.message('数据加载中,请稍后尝试...');
			return;
		}
		let param = this.getSearchParam();
		if(!param) {
			return;
		}
		this.isload = true;
		let paramStr = {
			parameters: param
		};
		let result = JSON.stringify(paramStr);
		let reqdata = 'gridPager=' + result;
		this.jsonApiService.http("gps/historyData.html", reqdata).subscribe(data => {
			this.isload = false;
			let len = data.length;
			if(len < 1) {
				this.jsonApiService.message('该时间段车辆没有数据');
				return;
			}
			this.tableData = data;
			this.totalCount = data.length;
			this.isTable = true;
			this.client_pages(0, this.pageSize);
		})
	}
	//表格部分end
	refresh() {
		this.load();
	}
	client_pages(start, length) {
		var len = start + Number(length);
		this.resultTableData = this.tableData.slice(start, len);
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.client_pages(e.first, e.rows);
	}
	//导出数据
	exprotCarData() {
		let myParam = this.getSearchParam();
		if(!myParam) {
			return;
		}
		let exportColumns = [];
		let reqdata = 'param=' + JSON.stringify(myParam) + '&columns=' + JSON.stringify(exportColumns);
		this.jsonApiService.http("gps/exportDataNoShow.html", reqdata).subscribe(data => {
			if(!data) {
				this.jsonApiService.message('没有查询到可导出的数据');
				return;
			}
			this.jsonApiService.message('数据导出成功.');
			var elemIF = document.createElement("iframe");
			elemIF.src = config.BaseURL + data.file;
			elemIF.style.display = "none";
			document.body.appendChild(elemIF);
		})
	}

	//获取查询参数
	getSearchParam() {
		this.startTime = $("#datetimepicker1").val();
		this.endTime = $("#datetimepicker2").val();
		let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 7);
		if(!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		if(this.deviceId === undefined || this.deviceId === "") {
			this.jsonApiService.message("请选择需要查询的车辆");
			return;
		}
		if(this.startTime === undefined || this.startTime === "") {
			this.jsonApiService.message("请选择起始时间");
			return;
		}
		if(this.endTime === undefined || this.endTime === "") {
			this.jsonApiService.message("请选择结束时间");
			return;
		}
		//获取时间戳
		let startTimestamp = new Date(this.startTime).getTime();
		let endTimestamp = new Date(this.endTime).getTime();
		if((endTimestamp - startTimestamp) < 0) {
			this.jsonApiService.message("时间选择不正确,结束时间应大于起始时间");
			return;
		}
		if((endTimestamp - startTimestamp) > 7 * 24 * 60 * 60 * 1000) {
			this.jsonApiService.message("时间区间不能超过7天");
			return;
		}
		var pager = new Object();
		var parameters = new Object();
		parameters['deviceId'] = this.deviceId;
		parameters['startTime'] = this.startTime;
		parameters['endTime'] = this.endTime;
		parameters['spaceTime'] = this.spaceTime + '';
		return parameters;
	}

	//判断是否有权限
	initBtn() {
		this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_car:history')));
		for(let item of this.btnData) {
			if(item.sourceKey === "download:ADValue" && item.parentId) {
				this.downloadADValue = true;
			}
		}
	}

	//初始化日期
	initDate() {
		var that = this;
		return new Promise(function(resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#datetimepicker1").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function(e) {
						var date = e.date;
						if(!date) {
							return;
						}
						var time = common.getTimeMmss(date);
						$("#datetimepicker2").datetimepicker("setStartDate", time);
					});
					$("#datetimepicker2").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function(e) {
						var date = e.date;
						if(!date) {
							return;
						}
						var time = common.getTimeMmss(date);
						$("#datetimepicker1").datetimepicker("setEndDate", time);
					});
					var date = new Date();
					$("#datetimepicker2").val(common.getTimeMmss(date)); //当前时间
					date.setDate(date.getDate() - 1); //设置前一周
					$("#datetimepicker1").val(common.getTimeMmss(date));
					resolve();
				});
			});
		})

	}

	ngOnInit() {
		$('#baiduMap').height($('.divTree').height());//地图高度和树形图高度保持一致
		let that = this;
		let mp = new BMap.Map('baiduMap',{enableMapClick: false}); //创建地图实例
		mp.centerAndZoom(new BMap.Point(117.7953288, 28.2862345), 5); //初始化地图，设置中心点坐标和地图级别
		mp.addControl(new BMap.NavigationControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,offset: new BMap.Size(12, 68)}));//缩放控件
		mp.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
		mp.addEventListener("zoomend", function() {
			that.mapSize = this.getZoom();
		});
		this.myMap = mp;
		this.initBtn();//权限按钮
		this.initAllCar();//车辆地图打点定位
		this.initDate();//初始化时间插件
		this.addEventWindowResize();//resize事件监听,动态改变树宽度
	}
	//resize事件监听,动态改变树宽度
	addEventWindowResize() {
		$(window).on('resize', function() {
			var wrapWidth = $("#wrap").width();
			var divTreeWidth = $(".divTree").width();
			$('.treeRight').width(wrapWidth - divTreeWidth - 36 + 'px');
		})
	}
	//drag事件监听,动态改变树宽度
	draggingEvent() {
		var clickX;
		var warp = $("#wrap");
		var treeElement = $(".divTree");
		var treeRight = $(".treeRight");
		var min = 300;
		var max = 0;
		var leftOffset = warp.offset().left;
		$(document).on('mousemove', function(e) {
			var wrapWidth = warp.width();
			max = wrapWidth / 2;
			var divTreeWidth = treeElement.width();
			var treeRightWidth = treeRight.width();
			clickX = e.pageX;
			//clickX-leftOffset > min   鼠标往右移动,并且大于最小宽度300
			if(clickX - leftOffset > min) {
				if(clickX - leftOffset < max) {
					treeElement.width(clickX - leftOffset + 'px');
					treeRight.width(wrapWidth - clickX + leftOffset - 36 + 'px');
				} else {
					treeElement.width(max + 'px');
					treeRight.width(wrapWidth - max - 36 + 'px');
				}
			} else {
				treeElement.width(min + 'px');
				treeRight.width(wrapWidth - min - 36 + 'px');
			}
		});

		$(document).mouseup(function(e) {
			e.cancelBubble = true;
			$(document).unbind('mousemove')
		})
	}
	ngOnDestroy() {
		$(document).unbind('keyup'); //移除键盘回车事件
		$(window).unbind('resize')
	}
}